package nl.altenpts.net.kad;

import java.util.List;

import nl.altenpts.net.NetReactor;
import nl.altenpts.net.broker.IncomingMessage;
import nl.altenpts.net.broker.ResponseHandler;

public class NodeOperation extends Operation {

	public NodeOperation(List<Node> nodes, Id target, NetReactor reactor, Callback callback, KBroker broker) {
		super(nodes, target, reactor, callback);
		
		this.broker = broker;
	}

	@Override
	protected void sendRequest(Node node) {
		if(node != null) {
			broker.NodeRequest(node, target, new NodeResponseHandler(node));
		} else {
			respond(nodes);
			finish();
		}		
	}

	private class NodeResponseHandler implements ResponseHandler {
		
		public NodeResponseHandler(Node n) {
			node = n;
		}

		public void onResponse(IncomingMessage response) {
			List<Node> newnodes = KBroker.parseNodeList(response.getPayload());
			addNodes(newnodes);
			nodeResponded(node, STATE_ANSWERED);
		}

		public void onTimeout() {
			nodeResponded(node, STATE_TIMEDOUT);
		}
		
		private Node node;
		
	}
	
	private KBroker broker;

}
